#include "devinfo.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdbool.h>

#define MAX_BUFFER_SIZE 256

// 执行shell命令并获取输出
static char* exec_command(const char* cmd) {
    FILE* fp = popen(cmd, "r");
    if (!fp) return NULL;
    
    char* result = malloc(MAX_BUFFER_SIZE);
    if (!result) {
        pclose(fp);
        return NULL;
    }
    
    if (fgets(result, MAX_BUFFER_SIZE, fp) == NULL) {
        free(result);
        pclose(fp);
        return NULL;
    }
    
    pclose(fp);
    return result;
}

// 获取当前音量百分比(0-100)
int get_volume(void) {
    char* result = exec_command("amixer get 'Power Amplifier' | grep 'Mono:' | awk '{print $3}' | tr -d '[]%'");
    if (!result) return -1;
    
    int volume = atoi(result);
    free(result);
    return volume;
}

// 设置音量(0-100)
bool set_volume(int volume) {
    if (volume < 0 || volume > 100) return false;
    
    char cmd[MAX_BUFFER_SIZE];
    snprintf(cmd, sizeof(cmd), "amixer set 'Power Amplifier' %d%%", volume);
    
    int ret = system(cmd);
    return (ret == 0);
}

// 读取文件内容到缓冲区
static bool read_file(const char* path, char* buf, size_t buf_size) {
    FILE* fp = fopen(path, "r");
    if (!fp) return false;
    
    if (fgets(buf, buf_size, fp) == NULL) {
        fclose(fp);
        return false;
    }
    
    // 去除换行符
    char* pos = strchr(buf, '\n');
    if (pos) *pos = '\0';
    
    fclose(fp);
    return true;
}

// 获取电池状态信息
BatteryStatus get_battery_status(void) {
    BatteryStatus status = {
        .status = "Unknown",
        .capacity = "Unknown"
    };
    
    // 读取电池状态
    if (!read_file("/sys/class/power_supply/axp20x-battery/status", 
                 status.status, sizeof(status.status))) {
        strcpy(status.status, "Unknown");
    }
    
    // 读取电池电量
    if (!read_file("/sys/class/power_supply/axp20x-battery/capacity", 
                 status.capacity, sizeof(status.capacity))) {
        strcpy(status.capacity, "Unknown");
    }
    
    return status;
}

int read_battery_status(char *status, int *capacity) {
    BatteryStatus bat = get_battery_status();
    strncpy(status, bat.status, 32);
    *capacity = atoi(bat.capacity);
    return 0;
}

int get_current_volume_s(void) {
    return get_volume();
}
